<?php
namespace app\extensions\lib;
use Google_Client;
use support\Log;
use support\Redis;

/**
1. Google FCM 工具类
 */
class FcmAccessToken
{
    const ACCESS_TOKEN_KEY = 'fcm_push_access_token_';
    const LOCK_KEY = 'lock_fcm_access_token_';
    public static function getAccessToken($package_id,$is_async,$configuration){
        $cacheKey = FcmAccessToken::getCacheKey($package_id,$is_async);
        $oldValue = Redis::get($cacheKey);
        if($oldValue){
            return $oldValue;
        }

        $RedisLock = new RedisLock();
        $lockKey = FcmAccessToken::getLockKey($package_id);
        //使用悲观锁
        $access_token = $RedisLock->actionLock($lockKey,function () use ($package_id,$configuration,$cacheKey){
            $oldValue = Redis::get($cacheKey);
            if($oldValue) return $oldValue;//其他锁已经生成就不用了
            $client = new Google_Client();
            $client->useApplicationDefaultCredentials();
            $client->setAuthConfig($configuration);
            $client->setScopes(['https://www.googleapis.com/auth/firebase.messaging','https://www.googleapis.com/auth/cloud-platform']);     # 授予访问 FCM 的权限
            $data =  $client->fetchAccessTokenWithAssertion();
            if(isset($data['expires_in']) && isset($data['access_token'])){

            }else{
                Log::channel('fcm')->error('getAccessToken_error'.json_encode($data));
            }
            $time = $data['expires_in'] - 65;
            Redis::set($cacheKey,$data['access_token']);
            Redis::expire($cacheKey,$time);
            return $data['access_token'];
        });



        return $access_token;
    }


    public static function getCacheKey($package_id,$is_async){
        return FcmAccessToken::ACCESS_TOKEN_KEY.$package_id.'_'.$is_async;
    }

    public static function getLockKey($package_id){
        return FcmAccessToken::LOCK_KEY.$package_id;
    }

}